package com.smilekay.serialtool;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.naz.serial.port.SerialPort;
import com.naz.serial.port.SerialPortFinder;
import com.smilekay.serialtool.databinding.ActivityMainBinding;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, DataPackageParser {
    ActivityMainBinding binding;
    ArrayAdapter<String> adapter;
    List<String> list = new ArrayList<>();
    SerialPort serialPort;
    InputStream inputStream;
    OutputStream outputStream;
    ReceiveThread thread;
    DataPackageParser dataPackageParser;
    StringBuilder sb = new StringBuilder("接收数据：\n");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        SerialPortFinder finder = new SerialPortFinder();
        String[] allDevicesPath = finder.getAllDevicesPath();
        for (String s : allDevicesPath) {
            list.add(s);
        }
        if (list.size() == 0) {
            list.add("/dev/ttyMSM1");
            list.add("/dev/ttyMT0");
            list.add("/dev/ttyS1");
            list.add("/dev/ttyS2");
            list.add("/dev/ttyS3");
            list.add("/dev/ttyS4");
            list.add("/dev/ttyS5");
        }
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, list);
        binding.listDevice.setAdapter(adapter);
        binding.btnConnect.setOnClickListener(this);
        binding.btnSend.setOnClickListener(this);
        binding.btnClear.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_connect:
                try {
                    if (binding.btnConnect.getText().equals("连接")) {
                        if (list.size() > 0) {
                            String path = binding.listDevice.getSelectedItem().toString();
                            serialPort = new SerialPort(new File(path), 115200, 0);
                            inputStream = serialPort.getInputStream();
                            outputStream = serialPort.getOutputStream();
                            dataPackageParser = this;
                            thread = new ReceiveThread();
                            thread.start();
                            Toast.makeText(this, path + " open success", Toast.LENGTH_SHORT).show();
                            binding.btnConnect.setText("断开");
                        }
                    } else {
                        inputStream.close();
                        outputStream.close();
                        inputStream = null;
                        outputStream = null;
                        serialPort.close();
                        thread.interrupt();
                        binding.btnConnect.setText("连接");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(this, "Open failed", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_send:
                try {
                    if (outputStream != null) {
                        String data = binding.etInput.getText().toString();
                        byte[] bytes = StringUtil.hexStringToBytes(data);
                        outputStream.write(bytes);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    binding.etInput.setText("");
                    Toast.makeText(this, "数据错误", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_clear:
                sb = new StringBuilder("接收数据：\n");
                binding.tvData.setText(sb.toString());
                break;
        }
    }

    @Override
    public void receiveDataCallback(byte[] var1) {
        String s = StringUtil.bytesToHex(var1);
        runOnUiThread(() -> {
            binding.tvData.setText(sb.append(s).append("\n").toString());
        });
        Log.d("smilekay", "Receive: " + s);
    }

    class ReceiveThread extends Thread {

        @Override
        public void run() {
            byte[] btAryBuffer = new byte[4096];

            while (true) {
                try {
                    int nLenRead = inputStream.read(btAryBuffer);
                    if (nLenRead > 0) {
                        byte[] btAryReceiveData = new byte[nLenRead];
                        System.arraycopy(btAryBuffer, 0, btAryReceiveData, 0, nLenRead);
                        dataPackageParser.receiveDataCallback(btAryReceiveData);
                    }
                } catch (IOException var1) {
                    var1.printStackTrace();
                    return;
                } catch (Exception var2) {
                    var2.printStackTrace();
                    return;
                }
            }
        }
    }
}